package com.ndhutu.ee.util;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileUtil {
    private static Logger log = LoggerFactory.getLogger(FileUtil.class);
    /**
     * 异步下载文件
     * @Author Shane
     * @Date 2019/8/2620:36
     * @param url   下载路径
     * @return
     **/
    public static String asyncDownload(String url, String path){
        Request request = new Request.Builder().url(url).build();

        final String path2;
        if(StringUtil.isEmpty(path)){
            path2 = "/download/"+DateUtil.getCurrTimeStr("yyyy")+"/"+DateUtil.getCurrTimeStr("MM")+"/"+DateUtil.getCurrTimeStr("dd")+"/"+DateUtil.getCurrTimeStr("HHmmss");
        }else{
            path2 = path;
        }
        final String fileName = url.indexOf("?") >= 0 ? url.substring(url.lastIndexOf("/")+1, url.lastIndexOf("?")) : url.substring(url.lastIndexOf("/")+1);

        new OkHttpClient().newCall(request).enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {

            }

            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    writeFile(response, path2, fileName);
                }
            }
        });

        return path2+"/"+fileName;
    }

    /**
     * 同步下载文件
     * @Author Shane
     * @Date 2019/8/2620:36
     * @param url   下载路径
     * @return
     **/
    public static String syncDownload(String url, String path){
        Request request = new Request.Builder().url(url).build();

        final String path2;
        if(StringUtil.isEmpty(path)){
            path2 = "/download/"+DateUtil.getCurrTimeStr("yyyy")+"/"+DateUtil.getCurrTimeStr("MM")+"/"+DateUtil.getCurrTimeStr("dd")+"/"+DateUtil.getCurrTimeStr("HHmmss");
        }else{
            path2 = path;
        }
        final String fileName = url.indexOf("?") >= 0 ? url.substring(url.lastIndexOf("/")+1, url.lastIndexOf("?")) : url.substring(url.lastIndexOf("/")+1);

        OkHttpClient okHttpClient = new OkHttpClient();
        try {
            Response response = okHttpClient.newCall(request).execute();
            writeFile(response, path2, fileName);
        }catch (IOException e){
            log.error("文件同步下载报错", e);
        }

        return path2+"/"+fileName;
    }

    /**
     * 写文件
     * @Author Shane
     * @Date 2019/8/2620:36
     * @param path  保存路径
     * @param fileName  文件名
     * @return
     **/
    public static String writeFile(Response response, String path, String fileName){
        InputStream is = null;
        FileOutputStream fos = null;
        byte[] buf = new byte[2048];
        int len = 0;

        File pathDir = new File(path);
        if(!pathDir.exists()){
            pathDir.mkdirs();
        }
        try {
            is = response.body().byteStream();
            long total = response.body().contentLength();
            fos = new FileOutputStream(new File(path, fileName));
            int sum = 0;
            while ((len = is.read(buf)) != -1) {
                fos.write(buf, 0, len);
                sum += len;
            }
            fos.flush();
        } catch (Exception e) {
            log.error("文件下载报错", e);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                log.error("下载文件关流报错", e);
            }
        }

        return path+"/"+fileName;
    }


    public static void main(String[] args) throws Exception{
//        System.out.println(download("http://pp-friend.nos-eastchina1.126.net/2019/08/26/210208/已关注.png", "/aa/bb"));

        String url = "https://security-data.oss-cn-shenzhen.aliyuncs.com/pay/ali/2019091067087964/alipayRootCert.crt";
        String path = url.substring(url.indexOf("/", 8), url.lastIndexOf("/"));
        String fileName = url.substring(url.lastIndexOf("/")+1);

        File file = new File(path+"/"+fileName);
        if (!file.exists()) {
//            FileUtil.asyncDownload(url, path);

            FileUtil.syncDownload(url, path);
        }

        System.out.println(path+"/"+fileName);
    }
}
